import request from './lib/request'
// import cheerio from 'cheerio'
import event from './lib/event'

async function updateToke(url) {
  const response = await request({
    methods: 'get',
    url
  })
  const csrftoken = response.match(/("csrftoken": '(\S*)')/)[0]

  process.config.csrftoken = csrftoken.substring(14, csrftoken.length - 1)
  event.emit('login')
}

export default {
  async checkImage(random) {
    process.config.cookie = undefined
    process.config.csrftoken = undefined
    const response = await request({
      methods: 'get',
      url: '/manage/checkImage?_=' + Math.random(),
      responseType: 'arraybuffer'
    })

    return response
  },
  async login(params) {
    const response = await request({
      methods: 'post',
      url: `/manage/check?username=${params.username}&password=${params.password}&code=${params.code}&source=common`
    })
    if (response.result.success) {
      updateToke(response.data.forwardUrl)
    }
    return response.result
  }
}
